package flc.ast.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.ToastUtils;
import com.stark.calculator.tax.SelectCityActivity;
import com.stark.calculator.tax.TaxCalRetActivity;
import com.stark.calculator.tax.adapter.WageRateAdapter;
import com.stark.calculator.tax.constant.TaxConst;
import com.stark.calculator.tax.model.CityWage;
import com.stark.calculator.tax.model.DataProvider;
import com.stark.calculator.tax.model.DeductionBean;
import com.stark.calculator.tax.model.TaxCalBean;
import com.stark.calculator.tax.model.WageRateBean;

import java.util.List;

import flc.ast.R;
import flc.ast.activity.IncomeKind1RetActivity;
import flc.ast.activity.MyDeductionActivity;
import flc.ast.activity.MySelectCityActivity;
import flc.ast.activity.QzdActivity;
import flc.ast.adapter.MyWageRateAdapter;
import flc.ast.databinding.FragmentIncomeKind1Binding;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.Str2NumUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link IncomeKind1Fragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class IncomeKind1Fragment extends BaseNoModelFragment<FragmentIncomeKind1Binding> {

    private static final int REQ_SEL_CITY = 1;
    private static final int REQ_SEL_QZD = 2;
    private static final int REQ_DEDUCTION = 3;
    private CityWage mSelCityWage;
    private MyWageRateAdapter mWageRateAdapter;
    private List<DeductionBean> mDeductionBeanList;
    private boolean isAll=true;

    private static final String[] sThresholdValues = new String[]{"5000", "6800"};


    @Override
    protected int onCreate() {
        return R.layout.fragment_income_kind1;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);
        //缴纳城市
        CityWage selCityWage = DataProvider.getSelCityWage();
        mSelCityWage = selCityWage;
        mDataBinding.tvIncomeKind1City.setText(selCityWage.cityName);
        //专项附加扣除
        mDeductionBeanList = DataProvider.getDeductions();
        updateDeduction();
        //缴纳项目
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        mDataBinding.rvPaymentItems.setLayoutManager(layoutManager);
        MyWageRateAdapter adapter = new MyWageRateAdapter(true);
        mWageRateAdapter = adapter;
        adapter.setDatas(DataProvider.getWageRateItems(selCityWage));

        mDataBinding.rvPaymentItems.setAdapter(adapter);
        mDataBinding.tvIncomeKind1Qbjn.setOnClickListener(this);
        mDataBinding.tvIncomeKind1Bfjn.setOnClickListener(this);
        mDataBinding.llIncomeKind1City.setOnClickListener(this);
        mDataBinding.llIncomeKind1Qzd.setOnClickListener(this);
        mDataBinding.llIncomeKind1Xiang.setOnClickListener(this);
        mDataBinding.llIncomeKind1Xm.setOnClickListener(this);
        mDataBinding.ivStartCal.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvIncomeKind1Qbjn:
                clearSelection();
                isAll=true;
                mDataBinding.tvIncomeKind1Qbjn.setTextColor(Color.WHITE);
                mDataBinding.tvIncomeKind1Qbjn.setBackgroundResource(R.drawable.daikuanfangshi1);
                break;
            case R.id.tvIncomeKind1Bfjn:
                clearSelection();
                isAll=false;
                mDataBinding.tvIncomeKind1Bfjn.setTextColor(Color.WHITE);
                mDataBinding.tvIncomeKind1Bfjn.setBackgroundResource(R.drawable.daikuanfangshi1);
                break;
            case R.id.llIncomeKind1City:
                selCity();
                break;
            case R.id.llIncomeKind1Qzd:
                Intent intent = new Intent(getActivity(), QzdActivity.class);
                if (mDataBinding.tvIncomeKind1Qzd.getText().toString().equals("5000")){
                    intent.putExtra("position",0);
                }else {
                    intent.putExtra("position",1);
                }
                startActivityForResult(intent,REQ_SEL_QZD);
                break;
            case R.id.llIncomeKind1Xiang:
                Intent intent1 = new Intent(getActivity(), MyDeductionActivity.class);
                startActivityForResult(intent1, REQ_DEDUCTION);
                break;
            case R.id.llIncomeKind1Xm:
                int visibility = mDataBinding.rvPaymentItems.getVisibility();
                if (visibility == View.VISIBLE) {
                    mDataBinding.ivIncomeKind1Xm.setImageResource(R.drawable.zhankai1);
                    mDataBinding.rvPaymentItems.setVisibility(View.GONE);
                } else {
                    mDataBinding.ivIncomeKind1Xm.setImageResource(R.drawable.zhankai2);
                    mDataBinding.rvPaymentItems.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.ivStartCal:
                calculate();
                break;
        }
    }

    @Override
    protected void initData() {

    }

    private void clearSelection() {
        mDataBinding.tvIncomeKind1Qbjn.setTextColor(Color.parseColor("#553CEB"));
        mDataBinding.tvIncomeKind1Qbjn.setBackground(null);
        mDataBinding.tvIncomeKind1Bfjn.setTextColor(Color.parseColor("#553CEB"));
        mDataBinding.tvIncomeKind1Bfjn.setBackground(null);
    }

    private void selCity() {
        Intent intent = new Intent(getActivity(), MySelectCityActivity.class);
        startActivityForResult(intent, REQ_SEL_CITY);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQ_SEL_CITY) {
                if (data == null) return;
                CityWage cityWage = (CityWage) data.getSerializableExtra(TaxConst.KEY_WAGE);
                DataProvider.saveSelCityWage(cityWage);
                mSelCityWage = cityWage;
                //通知相关UI更新
                mDataBinding.tvIncomeKind1City.setText(mSelCityWage.cityName);
                if (mWageRateAdapter != null) {
                    mWageRateAdapter.setDatas(DataProvider.getWageRateItems(mSelCityWage));
                }
            }else if (requestCode==REQ_SEL_QZD){
                mDataBinding.tvIncomeKind1Qzd.setText(sThresholdValues[data.getIntExtra("qzdPosition",0)]);
            } else if (requestCode == REQ_DEDUCTION) {
                if (data == null) return;
                mDeductionBeanList = data.getParcelableArrayListExtra(TaxConst.KEY_DEDUCTIONS);
                updateDeduction();
            }
        }
    }

    private void updateDeduction() {
        int count = 0;
        int amount = 0;
        if (mDeductionBeanList != null) {
            for (DeductionBean bean : mDeductionBeanList) {
                if (bean.isChecked()) {
                    try {
                        amount += Integer.parseInt(bean.getValue());
                        count++;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        String text = getString(R.string.deduction_amount_format, count, amount);
        mDataBinding.tvIncomeKind1Xiang.setText(text);
    }

    /**
     * 获取专项附加扣除金额
     *
     * @return
     */
    private float getDeduction() {
        float value = 0;
        if (mDeductionBeanList == null) {
            return value;
        }
        for (DeductionBean bean : mDeductionBeanList) {
            if (bean.isChecked()) {
                value += Str2NumUtil.parse(bean.getValue());
            }
        }
        return value;
    }

    private void calculate() {
        TaxCalBean calModel = new TaxCalBean();
        //税前工资
        String text = mDataBinding.etIncomeKin1Sqgz.getText().toString();
        if (TextUtils.isEmpty(text)) {
            mDataBinding.etIncomeKin1Sqgz.requestFocus();
            ToastUtils.showShort(R.string.input_pre_tax_salary);
            return;
        }
        float salary = 0;
        try {
            salary = Float.parseFloat(text);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (salary == 0) {
            mDataBinding.etIncomeKin1Sqgz.requestFocus();
            ToastUtils.showShort(R.string.input_pre_tax_salary);
            return;
        }
        calModel.preTaxSalary = salary;

        //实缴基数
        if (isAll) {
            /**
             * 全额缴纳：当前工资小于最低社保基数时，社保缴纳基数设为最低社保基数，
             * 当前工资大于最高社保基数时，社保缴纳基数设为最高社保基数，否则为税前工资本身
             */
            float minSheBao = Str2NumUtil.parse(mSelCityWage.rate.shebaoMin);
            float maxSheBao = Str2NumUtil.parse(mSelCityWage.rate.shebaoMax);
            if (salary < minSheBao) {
                calModel.sheBaoBase = minSheBao;
            } else if (salary > maxSheBao) {
                calModel.sheBaoBase = maxSheBao;
            } else {
                calModel.sheBaoBase = salary;
            }
            /**
             * 全额缴纳：当前工资小于最低公积金基数时，公积金缴纳基数设为最低公积金基数，
             * 当前工资大于最高公积金基数时，公积金缴纳基数设为最高公积金基数，否则为税前工资本身
             */
            float minGjj = Str2NumUtil.parse(mSelCityWage.rate.gongJiJinMin);
            float maxGjj = Str2NumUtil.parse(mSelCityWage.rate.gongJiJinMax);
            if (salary < minGjj) {
                calModel.gjjBase = minGjj;
            } else if (salary > maxGjj) {
                calModel.gjjBase = maxGjj;
            } else {
                calModel.gjjBase = salary;
            }

        } else {
            //部分缴纳
            //社保
            text = mDataBinding.etIncomeKin1Sjsb.getText().toString();
            if (TextUtils.isEmpty(text)) {
                mDataBinding.etIncomeKin1Sjsb.requestFocus();
                ToastUtils.showShort(R.string.input_valid_amount_tip);
                return;
            }
            calModel.sheBaoBase = Str2NumUtil.parse(text);
            //公积金
            text = mDataBinding.etIncomeKin1Sjgjj.getText().toString();
            if (TextUtils.isEmpty(text)) {
                mDataBinding.etIncomeKin1Sjgjj.requestFocus();
                ToastUtils.showShort(R.string.input_valid_amount_tip);
                return;
            }
            calModel.gjjBase = Str2NumUtil.parse(text);
        }

        //个税起征点
        text = mDataBinding.tvIncomeKind1Qzd.getText().toString();
        calModel.threshold = Str2NumUtil.parse(text);

        //附加扣除
        calModel.deduction = getDeduction();

        //社保、公积金比例
        List<WageRateBean> rateBeanList = mWageRateAdapter.getDatas();
        setTaxCalModelRate(calModel, rateBeanList);

        //TaxCalRetActivity.start(getContext(), calModel);
        goCalRetActivity(calModel);
    }

    protected void goCalRetActivity(TaxCalBean calBean) {
        IncomeKind1RetActivity.start(getContext(), calBean);
    }

    /**
     * 设置个税计算实例中的五险一金的各比例数据
     *
     * @param model
     * @param rateBeanList
     */
    private void setTaxCalModelRate(TaxCalBean model, List<WageRateBean> rateBeanList) {
        if (model == null || rateBeanList == null) {
            return;
        }
        for (WageRateBean rateBean : rateBeanList) {
            switch (rateBean.getType()) {
                case YANG_LAO:
                    model.yangLaoPersonal = Str2NumUtil.parse(rateBean.getPersonal());
                    model.yangLaoCompany = Str2NumUtil.parse(rateBean.getCompany());
                    break;
                case YI_LIAO:
                    model.yiLiaoPersonal = Str2NumUtil.parse(rateBean.getPersonal());
                    model.yiLiaoCompany = Str2NumUtil.parse(rateBean.getCompany());
                    break;
                case SHI_YE:
                    model.shiYePersonal = Str2NumUtil.parse(rateBean.getPersonal());
                    model.shiYeCompany = Str2NumUtil.parse(rateBean.getCompany());
                    break;
                case GONG_SHANG:
                    model.gongShangPersonal = Str2NumUtil.parse(rateBean.getPersonal());
                    model.gongShangCompany = Str2NumUtil.parse(rateBean.getCompany());
                    break;
                case SHENG_YU:
                    model.shengYuPersonal = Str2NumUtil.parse(rateBean.getPersonal());
                    model.shengYuCompany = Str2NumUtil.parse(rateBean.getCompany());
                    break;
                case GONG_JI_JIN:
                    model.gjjPersonal = Str2NumUtil.parse(rateBean.getPersonal());
                    model.gjjCompany = Str2NumUtil.parse(rateBean.getCompany());
                    break;
            }
        }
    }
}